﻿using DimensionsHelper.Common.Contracts.TableFormatter;

namespace DimensionsHelper.Client.WinUi.ViewModels;

public partial class TableFormatterFilesViewModel : ObservableObject
{
    public ObservableCollection<TableFormatterOutputFileViewModel> Files
    {
        get;
    } = [];


    public bool AnyValidFile() => Files.Any(f => !string.IsNullOrEmpty(f.FileName) && f.Files.Count > 0);


    private bool FileExists(string fileName) =>
        Files.Any(f => PathEqualityComparer.Instance.Equals(f.FileName, fileName));


    [RelayCommand]
    private async Task SelectInputFile()
    {
        string? file = await App.GetService<IFilePikerService>().SaveFileAsync(FileFilters.Excel);
        if (!string.IsNullOrEmpty(file) && !FileExists(file))
        {
            TableFormatterOutputFileViewModel viewModel = new()
            {
                ExistPredicate = FileExists,
                RemoveCallback = vm =>
                {
                    if (vm is TableFormatterOutputFileViewModel csvFile)
                    {
                        Files.Remove(csvFile);
                    }
                },
                Filter = FileFilters.Excel,
                FileName = file
            };

            Files.Add(viewModel);
        }
    }


    [RelayCommand]
    private void Clear() => Files.Clear();


    [RelayCommand]
    private static void Start() => App.GetService<TableFormatterViewModel>().Start();


    public IReadOnlyList<(string FileName, IReadOnlyList<TableInputFileInfo> Infos)> GetOutputFiles()
    {
        return Files.DistinctBy(f => f.FileName, PathEqualityComparer.Instance)
            .Select(f => (f.FileName, f.GetCsvInputFileInfos()))
            .ToList();
    }
}